﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Globalization;
using Microsoft.Practices.Unity.Configuration;
using Microsoft.Practices.Unity;
using System.Configuration;

namespace Wicresoft.UnifyShow2.Portal
{
    public class CustomControllerFactory : DefaultControllerFactory
    {
        private static IUnityContainer container;

        public CustomControllerFactory()
        {
            if (container != null) return;
            container = new UnityContainer();
            try{
                UnityConfigurationSection section
                              = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
                container.LoadConfiguration(section,"default");
            }
            catch (Exception ex){
                throw new ConfigurationErrorsException("unity miss", ex);
            }
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            //skip /favicon.ico which will cause exception
            if (requestContext.HttpContext.Request.Path == "/favicon.ico")
                return null;

            if (controllerType == null)
            {
                throw new HttpException(404,
                    String.Format(
                        CultureInfo.CurrentUICulture,
                        "The controller for path '{0}' was not found or does not implement IController.",
                        requestContext.HttpContext.Request.Path));
            }
            
if (!typeof(IController).IsAssignableFrom(controllerType))
            {
                throw new ArgumentException(
                    String.Format(
                        CultureInfo.CurrentUICulture,
                        "The controller type '{0}' must implement IController.",
                        controllerType),
                    "controllerType");
            }
            try
            {
               // Activator.CreateInstance(controllerType);
                //return (IController)kernel.Get(controllerType);
                return (IController)container.Resolve(controllerType);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(
                    String.Format(
                        CultureInfo.CurrentUICulture,
                        "An error occurred when trying to create a controller of type '{0}'. Make sure that the controller has a parameterless public constructor.",
                        controllerType),
                    ex);
            }
        }
    }
}